import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
import routes from './routes'

import store from '@/store'
import login from '@/store/login'
//重写push和repalce 因为会出现警告，虽然不影响正常使用
let originPush=VueRouter.prototype.push;
VueRouter.prototype.push=function(location,reject,resolve){
    if (reject&&resolve) {
        originPush.call(this,location,reject,resolve)
    }else{
        originPush.call(this,location,()=>{},()=>{})
    }
}

const router= new VueRouter({
    routes,//简写>>>>routes:routes
    //滚动行为：路由跳转之后在滚轮页面的位置
    scrollBehavior (to, from, savedPosition) {
        // return 期望滚动到哪个的位置
        return { x: 0, y: 0 }
    }
})
router.beforeEach(async (to,from,next)=>{
    // next();
    let token=store.state.login.token;
    let name=store.state.login.userInfo.name;
    console.log(token,name)
    if (token) {
        if (to.path=="/login"||to.path=="register") {
            next("/");
        }else{
            if (name) {
                next();
            }else{
                try {
                    await store.dispatch("getUserInfo");
                    // console.log(store)
                    next();
                } catch (error) {
                    await store.dispatch("getLoginOut");
                    console.log("登录过期，请重新登录");
                    next("/login");
                }
            }
            
        }
        
    }
    else{
        console.log(to)
        let toPath=to.path;
        if (toPath.indexOf("/pay")!=-1||toPath.indexOf("/trade")!=-1) {
            next("/login");
        }else if(toPath.indexOf("/center")!=-1||toPath.indexOf("/shopCart")!=-1){
            next("/login?toPath="+toPath);
        }else{
            next();
        }
        // if(to.meta.notLogin){
        //     next("/login");
        // }else{
        //     next(false);
        // }
    }
    // if (token) {
    //     if (to.path=='/login') {
    //         next('/');
    //     } else {
    //        if (name) {
    //            next();
    //        }else{
    //            try {
    //                 await this.$store.dispatch("getUserInfo");
    //                 next();
    //            } catch (error) {
    //                //如果获取不到用户信息，则应该是token过期了
    //             //    console.log(error);
    //                next('/login');
    //            }
    //        }
    //     }
    // } else {
    //     next();
    // }
})

export default router